package cn.dansj.common.utils.redis.serializer;

import cn.dansj.common.utils.json.JSONUtils;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.nio.charset.StandardCharsets;

public class StringSerializer<T> implements RedisSerializer<T> {
    private static final StringSerializer<String> instance = new StringSerializer<>();

    private StringSerializer() {

    }

    @Override
    public byte[] serialize(T object) {
        if (object == null) {
            return new byte[0];
        }

        if (object instanceof String) {
            return object.toString().getBytes(StandardCharsets.UTF_8);
        } else {
            return JSONUtils.toJSON(object).getBytes(StandardCharsets.UTF_8);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public T deserialize(byte[] bytes) {
        //为空或者长度为0直接返回null
        if (bytes == null || bytes.length == 0) {
            return (T) "";
        }

        return (T) new String(bytes, StandardCharsets.UTF_8);
    }

    public static RedisSerializer<String> getInstance() {
        return instance;
    }
}